let socketOpen = false;
let socketMsgQueue = [];

import socket from 'plus-websocket';
import Stomp from 'stompjs';

Object.assign(uni, socket);

const StompClient = {
	client: null,
	init(url, headers) {
		if (this.client && this.client.connected) {
			return Promise.resolve(this.client);
		}

		return new Promise((resolve, reject) => {
			const ws = {
				send: this.sendMessage,
				onopen: null,
				onmessage: null,
				close: this.closeSocket,
			};

			uni.connectSocket({
				url: url,
				header: headers,
				success: () => {
					console.log('Succeed to uni.connectSocket');
				},
				fail: (err) => {
					console.log('Failed to uni.connectSocket:', JSON.stringify(err));
				}
			});

			uni.onSocketOpen(function(res) {
				if(!socketOpen) {
					socketOpen = true;
					console.log('uni.onSocketOpen:' + JSON.stringify(res));
					
					for (let i = 0; i < socketMsgQueue.length; i++) {
						ws.send(socketMsgQueue[i]);
					}
					socketMsgQueue = [];
					
					ws.onopen && ws.onopen();
				}
			});

			uni.onSocketMessage(function(res) {
				ws.onmessage && ws.onmessage(res);
			});

			uni.onSocketError(function(res) {
				console.log('uni.onSocketError:' + JSON.stringify(res));
			});

			uni.onSocketClose((res) => {
				if (this.client && this.client.connected)
					this.client.disconnect();
				this.client = null;
				socketOpen = false;
				console.log('uni.onSocketClose:', res);
			});

			Stomp.setInterval = function(interval, f) {
				return setInterval(f, interval);
			};
			Stomp.clearInterval = function(id) {
				return clearInterval(id);
			};

			const client = this.client = Stomp.over(ws);
			client.connect(headers, function() {
				console.log('stomp connected');
				resolve(client);
			});
		});
	},
	disconnect() {
		uni.closeSocket();
	},
	sendMessage(message) {
		if (socketOpen) {
			uni.sendSocketMessage({
				data: message,
			});
		} else {
			socketMsgQueue.push(message);
		}
	},
	closeSocket() {
        uni.closeSocket();
        console.log('closeSocket');
	},
	sendDisconnect(callback) {
		this.client.disconnect(callback());
	},
	sendStompMessage(dest, headers, content) {
		this.client.send(dest, headers, content);
	},
	subscribeDestination(dest, callback) {
		this.client.subscribe(dest, function(message) {
			console.log('Received subscribed topic message:' + JSON.stringify(message));
			callback(message);
		});
	}
};

export default StompClient